import axios from 'axios';
import qs from 'qs'
import { useUserOut } from '@/store/user';

const axiosInstance = axios.create({
    timeout: 60,
    baseURL: '/'
})

axiosInstance.interceptors.request.use(config => {
    if (
        config.method === 'post' &&
        config.headers['Content-Type'] === 'application/x-www-form-urlencoded'
      ) {
        config.data = qs.stringify(config.data)
      } 
      if (config.method === 'get' && config.params) {
        let url = config.url
        url += '?'
        const keys = Object.keys(config.params)
        for (const key of keys) {
          if (config.params[key] !== void 0 && config.params[key] !== null) {
            url += `${key}=${encodeURIComponent(config.params[key])}&`
          }
        }
        url = url.substring(0, url.length - 1)
        config.params = {}
        config.url = url
      }
      return config
})

axiosInstance.interceptors.response.use(response => {
    if (response.status >= 200 && response.status < 300) {
        return response
    } else {
        console.log(response?.data?.message);
        if (response?.status === 401) {
            const userStore = useUserOut()
            userStore.logout()
            // 重新认证
            window.location.reload();
        }
    }
})

const request = (config) => {
    const { url, method, params, data, headers, responseType } = config
    return new Promise((resolve, reject) => {
        axiosInstance.request({
            url: url,
            method,
            timeout: 60000,
            params,
            data: data,
            responseType: responseType,
            headers: {
              'Content-Type': 'application/json',
              ...headers
            }
          }).then(res => {
            resolve(res)
          }).catch(err => {
            reject(err)
          })
    })
}

export default {
    get: (option) => {
      return request({ method: 'get', ...option })
    },
    post: (option) => {
      return request({ method: 'post', ...option }) 
    },
    delete: (option) => {
      return request({ method: 'delete', ...option }) 
    },
    put: (option ) => {
      return request({ method: 'put', ...option }) 
    }
  }